from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.dataCheck import DataCheck
from notice.models import NoticeInfo
from user.models import Company
import pdb, os, json

import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")

datacheck = DataCheck()


def addNotice(request, *args, **kwargs):
    """
        url    : /notice/publish/
        method : POST

    :param request:
            token:data.token,//token
            noticeTitle:data.title,
            noticeContent:data.noticeContent,//问题内容

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if userType == '2':
        notice = NoticeInfo.objects.create(
            user=user,
            noticeTitle=requestParam['noticeTitle'],
            noticeContent=requestParam['noticeContent'],
        )
        for company in json.loads(requestParam['isView']):
            companys = Company.objects.filter(pk=company)
            companyItem = companys[0]
            notice.isview.add(companyItem)
        notice.save()

    else:
        data = {
            'code': 0,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def getNotice(request, *args, **kwargs):
    """
        url    : /notice/get/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'noticelist':[{
                    'id':null,//
                    'title':null,
                    'time':null,
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    user = datacheck.getUser(requestParam['token'])
    company = user.company

    filterDict = {}

    if requestParam['noticeState'] != '':
        if requestParam['noticeState'] == '0':
            filterDict['isActive'] = True
            filterDict['noticeState'] = 0
            filterDict['isview'] = company
        elif requestParam['noticeState'] == '1':
            filterDict['isActive'] = True
            filterDict['noticeState'] = 1
            filterDict['isview'] = company
        else:
            data = {
                "code": 1,
                "msg": "state Error",
                'totalNum': 0,
                'noticelist': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    elif requestParam['noticeState'] == '':
        filterDict['isActive'] = True
        # pdb.set_trace()
    noticelist = NoticeInfo.objects.filter(**filterDict).order_by('-createTime')
    if noticelist.exists():
        totalNum = len(noticelist)
        noticelists = []
        result = noticelist[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]

        for notice in result:
            noticeItem = NoticeInfo.objects.filter(isRead=user,id=notice.id)
            if noticeItem.exists():
                isRead = 1
            else:
                isRead = 0 
            noticelist = {
                'id': notice.id,
                'title': notice.noticeTitle,
                'noticeState': notice.noticeState,
                'time': notice.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                "isRead":isRead
            }
            noticelists.append(noticelist)
    else:
        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "noticelist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "noticelist": noticelists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def noticeContent(request, *args, **kwargs):
    """
        url    : /notice/content/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
                noticeId: data.noticeId, // 仓库Id 

    :return:
              'code': null, // 标志返回状态、0：成功 1：失败
              'msg': null, // 返回消息
              'title':null,//
              'content':null,
              'time':null,
              'username':null,//发布用户        
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    notice = NoticeInfo.objects.get(pk=requestParam['noticeId'])
    # pdb.set_trace()
    data = {
        "code": 0,
        "msg": "success",
        "title": notice.noticeTitle,
        "content": notice.noticeContent,
        "time": notice.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
        "username": notice.user.name,
    }
    logger_request.info(data)
    return JsonResponse(data)


def optionNotice(request, *args, **kwargs):
    """
        url    : /notice/option/
        method : POST

    :param request:
            token:data.token,//秘钥
            noticeId:data.noticeId,//
            option:data.option,//0启用 1禁用 2删除

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    notice = NoticeInfo.objects.get(pk=requestParam['noticeId'])
    if userType == '2':
        if requestParam['option'] == '0' and notice.isActive == True and notice.noticeState == 1:
            notice.noticeState = 0
            notice.save()

        elif requestParam['option'] == '1' and notice.isActive == True and notice.noticeState == 0:
            notice.noticeState = 1
            notice.save()

        elif requestParam['option'] == '2' and notice.isActive == True:
            notice.isActive = False
            notice.save()
    else:

        data = {
            'code': 0,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)
